package com.cskaoyan.service.admin;

import com.cskaoyan.bean.admin.Permission;
import com.cskaoyan.bean.admin.PermissionExample;
import com.cskaoyan.bean.admin.bo.PermissionsBo;
import com.cskaoyan.mapper.admin.PermissionMapper;
import com.cskaoyan.utils.ReflectionSetJavaBeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * 类<code>Doc</code>用于：TODO 授权api信息
 *
 * @author Acher
 * @version 1.0
 * @date 2021-10-22
 */
@Service
public class PermissionServiceImpl implements PermissionService{

    @Autowired
    PermissionMapper permissionMapper;

    @Transactional(isolation = Isolation.REPEATABLE_READ,
            propagation = Propagation.REQUIRED)// 设置事务，保证删除和插入同时成功，确保数据安全
    @Override
    public void replace(PermissionsBo permissionsBo) {
        // 根据roleId添加或删除permission表数据
        // 直接替换表内数据 👉 先删后增
        Integer roleId = permissionsBo.getRoleId();
        PermissionExample example = new PermissionExample();
        example.createCriteria().andRoleIdEqualTo(roleId);
        int deletedAffectedRows = permissionMapper.deleteByExample(example);// 根据roleId批量删除
        List<String> permissions = permissionsBo.getPermissions();
        int insertAffectedRows = 0;
        for (String permission : permissions) {// 批量插入
            Permission bean = new Permission();
            bean.setRoleId(roleId);
            bean.setPermission(permission);
            ReflectionSetJavaBeanUtils.setJavaBean(bean);
            insertAffectedRows = permissionMapper.insert(bean);
        }
    }
}
